package com.quectel.cms.controller.schedulingapply;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.business.common.schedulingapply.SchedulingApplyBusiness;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.util.SessionHolder;
import com.quectel.constant.core.scheduling.SchedulingApplyConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.file.vo.FileDataVO;
import com.quectel.core.module.schedulingapply.dto.SchedulingApplyRecordDto;
import com.quectel.core.module.schedulingapply.service.SchedulingApplyRecordService;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import com.quectel.util.common.ServletUtils;
import com.quectel.util.kit.StorageKit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/07/13 19:14
 */
@RestController
@RequestMapping("schedulingApplyRecord")
@Tag(name = "SchedulingApplyRecordController", description = "申请记录相关api")
public class SchedulingApplyRecordController extends BaseController {

    @DubboReference
    private SchedulingApplyRecordService schedulingApplyRecordService;

    @Autowired
    private SchedulingApplyBusiness schedulingApplyBusiness;

    @GetMapping("getResource/{id}/{url}")
    @Operation(summary = "资源访问")
    public void getResource(@PathVariable Long id, String url, HttpServletResponse httpServletResponse) {
        SchedulingApplyRecordDto applyRecordDto = schedulingApplyRecordService.selectById(id);
        //填充表单数据
        SchedulingApplyRecordDto.BaseFormData formData = schedulingApplyBusiness.getFormData(applyRecordDto.getApplyType(), applyRecordDto.getFormDataJson());
        List<FileDataVO> extFiles = formData.getExtFiles();
        FileDataVO result = null;
        if (CollectionUtils.isNotEmpty(extFiles)) {
            for (FileDataVO extFile : extFiles) {
                if (extFile.getUrl().equals(url)) {
                    result = extFile;
                }
            }
        }
        if (result == null) {
            try {
                httpServletResponse.getOutputStream().write(SystemConstants.ILLEGAL_MSG.getBytes(StandardCharsets.UTF_8));
            } catch (IOException e) {
                logger.error("SchedulingApplyRecord file preview status is disable, response write error.");
            }
            return;
        }
        ServletUtils.write(
                httpServletResponse,
                StorageKit.getObject(result.getUrl()),
                result.getName()
        );
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "schedulingApplyRecord:list")
    @Operation(summary = "分页获取申请记录列表")
    public Response<Page<SchedulingApplyRecordDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        String applyStatus = request.getString(SchedulingApplyConstants.APPLY_STATUS);
        if (StringUtils.isNotEmpty(applyStatus)) {
            if (applyStatus.equals(SchedulingApplyConstants.CMS_AUDITING)) {
                request.put(SystemConstants.STATUSES, new Byte[]{SchedulingApplyConstants.INIT_STATUS});
            } else if (applyStatus.equals(SchedulingApplyConstants.CMS_APPROVED)) {
                request.put(SystemConstants.STATUSES, new Byte[]{SchedulingApplyConstants.APPROVED_STATUS, SchedulingApplyConstants.WRITE_OFF_STATUS});
            } else if (applyStatus.equals(SchedulingApplyConstants.CMS_REJECTED)) {
                request.put(SystemConstants.STATUSES, new Byte[]{SchedulingApplyConstants.REJECT_STATUS});
            }
        } else {
            request.put(SystemConstants.STATUSES, new Byte[]{
                    SchedulingApplyConstants.CLOSE_STATUS,
                    SchedulingApplyConstants.CANCEL_STATUS,
                    SchedulingApplyConstants.INIT_STATUS,
                    SchedulingApplyConstants.APPROVED_STATUS,
                    SchedulingApplyConstants.REJECT_STATUS,
                    SchedulingApplyConstants.WRITE_OFF_STATUS,
            });
        }
        request.put(LambdaUtil.getFieldName(SchedulingApplyRecordDto::getTenantId), SessionHolder.getSysUser().getTenantId());


        int total = schedulingApplyRecordService.queryTotal(request.getParams());

        List<SchedulingApplyRecordDto> list = null;
        if (total > 0) {
            list = schedulingApplyRecordService.queryList(request.getParams());
            list.forEach(schedulingApplyRecordDto -> {
                //填充表单数据
                SchedulingApplyRecordDto.BaseFormData formData = schedulingApplyBusiness.getFormData(schedulingApplyRecordDto.getApplyType(), schedulingApplyRecordDto.getFormDataJson());
                schedulingApplyRecordDto.setFormData(formData);
            });
        } else {
            list = new ArrayList<>();
        }

        Page<SchedulingApplyRecordDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<SchedulingApplyRecordDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "schedulingApplyRecord:edit")
    @Operation(summary = "在编辑时根据id查询申请记录详情")
    public Response<SchedulingApplyRecordDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (schedulingApplyRecordService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SchedulingApplyRecordDto schedulingApplyRecordDto = schedulingApplyRecordService.selectById(id);
        //填充表单数据
        SchedulingApplyRecordDto.BaseFormData formData = schedulingApplyBusiness.getFormData(schedulingApplyRecordDto.getApplyType(), schedulingApplyRecordDto.getFormDataJson());
        schedulingApplyRecordDto.setFormData(formData);

        return Response.<SchedulingApplyRecordDto>ok().wrap(schedulingApplyRecordDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "schedulingApplyRecord:info")
    @Operation(summary = "根据id查询申请记录的详情")
    public Response<SchedulingApplyRecordDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (schedulingApplyRecordService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SchedulingApplyRecordDto schedulingApplyRecordDto = schedulingApplyRecordService.selectById(id);
        //填充表单数据
        SchedulingApplyRecordDto.BaseFormData formData = schedulingApplyBusiness.getFormData(schedulingApplyRecordDto.getApplyType(), schedulingApplyRecordDto.getFormDataJson());
        schedulingApplyRecordDto.setFormData(formData);

        return Response.<SchedulingApplyRecordDto>ok().wrap(schedulingApplyRecordDto);
    }

    /**
     * 保存
     *
     * @param schedulingApplyRecordDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "schedulingApplyRecord:edit")
    @Operation(summary = "新增申请记录")
    public Response<Object> save(@RequestBody @Validated SchedulingApplyRecordDto schedulingApplyRecordDto) {

        //填充基础数据
        fillSaveCommonData(schedulingApplyRecordDto);

        schedulingApplyRecordService.save(schedulingApplyRecordDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param schedulingApplyRecordDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "schedulingApplyRecord:edit")
    @Operation(summary = "根据id修改申请记录")
    public Response<Object> update(@RequestBody @Validated SchedulingApplyRecordDto schedulingApplyRecordDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(schedulingApplyRecordDto.getId()));
        if (schedulingApplyRecordService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(schedulingApplyRecordDto);

        schedulingApplyRecordService.updateById(schedulingApplyRecordDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "schedulingApplyRecord:delete")
    @Operation(summary = "根据多条记录id批量删除申请记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (schedulingApplyRecordService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        schedulingApplyRecordService.deleteBatch(ids);

        return Response.ok();
    }
}
